import { baseURL } from '@/utils/request';
import { getAuth } from '@/utils/storage';
import { useEffect } from 'react';
import { useHistory } from 'react-router-dom';
import { io } from 'socket.io-client';

export default function Test() {
  const history = useHistory();
  useEffect(() => {
    console.log('挂载组件');
    const client = io(baseURL, {
      transports: ['websocket'],
      // 在查询字符串参数中传递 token
      query: {
        token: getAuth()?.token,
      },
    });
    // 监听服务器发送的消息
    client.on('connect', () => {
      console.log('服务器发送的消息');
    });
    // 监听收到消息的事件
    client.on('message', (data) => {
      console.log('>>>>收到 socket.io 消息:', data);
    });
    return () => {
      console.log('卸载组件');
      client.close();
    };
  }, []);

  return (
    <div>
      <button onClick={() => history.push('/login')}>点我卸载组件</button>
    </div>
  );
}
